// MIT License
// 开源地址：https://gitee.com/co1024/AbcMvc
// Copyright (c) 2021-2023 1024
// Abc.Mvc=Furion+EF+SqlSugar+Pear layui admin.

using Furion;

using MiniExcelLibs;

namespace Abc.Web.Mvc.Areas.HtAdmin.Controllers
{
    /// <summary>
    /// Mini Excel
    /// </summary>
    [NonValidation]
    //[AuthorizePolicy]
    [AllowAnonymous]
    [MaMvc(area: "HtAdmin", controllerDescription: "MiniExcel", PCode = "HtAdmin_Developer")]
    public class MiniExcelController : HtAdminBaseController
    {
        private readonly ILogger<MiniExcelController> _logger;

        public MiniExcelController(ILogger<MiniExcelController> logger)
        {
            _logger = logger;
        }

        [MaMenu(name: "miniExcel示例", Code = "TestExcel", UrlPar = "")]
        [MaPermission(name: "miniExcel示例", actions: "TestExcel,UploadFile,DownloadExcel,DownloadExcel2,DownloadExcel3")]
        [HttpGet]
        public async Task<IActionResult> TestExcel()
        {
            return View();
        }

        /// <summary>
        /// 上传excel，读取后，另存为excel
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        [HttpPost]
        [IgnoreAntiforgeryToken]
        public async Task<JsonResult> UploadFile(string type)
        {
            var uploadresult = await WebUpLoad.FileUpload(new WebUploadInput(FloderName: type));
            //读取excel数据 为  IEnumerable<dynamic>
            var rows = MiniExcel.Query(uploadresult.newFilePath, sheetName: "Sheet1", useHeaderRow: true);//读取为动态类型
            var rows2 = MiniExcel.Query<ExcelModelView>(uploadresult.newFilePath, sheetName: "Sheet1");//读取为对象

            var count = rows.Count();

            //保存集合到 excle文件
            var savepath = $"{App.WebHostEnvironment.WebRootPath}/{DateTime.Now:yyyyMMddHHmmssfff}.xlsx";
            MiniExcel.SaveAs(savepath, rows);


            return Json(uploadresult.GetDefaultResult());
            //return Json(new { code = 1, msg = uploadresult.Errors, data = uploadresult.Data });
        }


        /// <summary>
        /// 直接下载exel
        /// </summary>
        /// <returns></returns>
        public IActionResult DownloadExcel()
        {
            var values = new[] {
        new { Column1 = "MiniExcel", Column2 = 1 },
        new { Column1 = "Github", Column2 = 2}
    };

            var memoryStream = new MemoryStream();
            memoryStream.SaveAs(values, sheetName: "Demo");
            memoryStream.Seek(0, SeekOrigin.Begin);
            return new FileStreamResult(memoryStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
            {
                FileDownloadName = "demo.xlsx"
            };
        }
        /// <summary>
        /// 读取excel数据，然后直接下载
        /// </summary>
        /// <returns></returns>
        public IActionResult DownloadExcel2()
        {
            var exceltest = $"{App.WebHostEnvironment.WebRootPath}\\Templates\\ExcelTest_01.xlsx";
            var rows = MiniExcel.Query(exceltest, sheetName: "Sheet1", useHeaderRow: true);

            var memoryStream = new MemoryStream();
            memoryStream.SaveAs(rows, sheetName: "Demo2");
            memoryStream.Seek(0, SeekOrigin.Begin);
            return new FileStreamResult(memoryStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
            {
                FileDownloadName = "demo2.xlsx"
            };
        }
        /// <summary>
        /// 加载excel数据，使用模板，保存到内存，然后直接下载
        /// </summary>
        /// <returns></returns>
        public IActionResult DownloadExcel3()
        {
            var exceltest = $"{App.WebHostEnvironment.WebRootPath}\\Templates\\ExcelTest_01.xlsx";
            var rows = MiniExcel.Query<ExcelModelView>(exceltest, sheetName: "Sheet1");

            string templatePath = $"{App.WebHostEnvironment.WebRootPath}\\Templates\\ExcelTest_OutTemplate_01.xlsx";
            //byte[] bytes = System.IO.File.ReadAllBytes(templatePath);

            //注意：模板填充 外面要封装一层 value,否则会报错的 https://gitee.com/dotnetchina/MiniExcel#2-ienumerable-%E6%95%B0%E6%8D%AE%E5%A1%AB%E5%85%85

            //下面这个rows可以是自己的数据

            var value = new {
                test = rows
            };
            var memoryStream = new MemoryStream();
            memoryStream.SaveAsByTemplate(templatePath, value);
            memoryStream.Seek(0, SeekOrigin.Begin);
            return new FileStreamResult(memoryStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
            {
                FileDownloadName = "demo2.xlsx"
            };
        }
        /// <summary>
        /// 测试的Excel读取的实体对象，与 wwwroot 中Templates\\ExcelTest_01.xlsx 文件列对应
        /// </summary>
        public class ExcelModelView
        {
            public string Name { get; set; }

            public string Title { get; set; }

            public string Remark { get; set; }

            public string A { get; set; }

            public string B { get; set; }

            public string C { get; set; }
            public string D { get; set; }

            public string E { get; set; }

            public string F { get; set; }

            public string G { get; set; }
        }

    }
}
